package com.boot.controller;

import com.boot.entity.ChartRequest;
import com.boot.entity.ChartResponse;
import com.boot.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;

@Controller
public class WsController {

    //SimpMessagingTemplate：SpringBoot提供操作WebSocket的对象
    @Autowired
    private SimpMessagingTemplate template;

    //广播推送消息
    @Scheduled(fixedRate = 10000)
    public void sendTopicMessage() {
        System.out.println("后台广播推送！");
        this.template.convertAndSend(
                "/topic/ssbj",
                User.builder()
                        .name("张三")
                        .conent("后台广播推送")
                        .build());
    }

    //一对一推送消息
    //定时10S执行这个方法，向客户端推送
    @Scheduled(fixedRate = 10000)
    public void sendQueueMessage() {
        System.out.println("后台一对一推送！");
        User user = new User();
        user.setUserId("admin");
        user.setName("超级管理员");
        user.setConent("一对一推送");
        template.convertAndSendToUser(user.getUserId(), "/queue", user);
    }

    //客户端主动发送消息到服务端，服务端马上回应指定的客户端消息
    //类似http无状态请求，但是有质的区别
    //websocket可以从服务器指定发送哪个客户端，而不像http只能响应请求端

    //群发
    @MessageMapping("/massRequest")
    //SendTo 发送至 Broker 下的指定订阅路径
    @SendTo("/mass/getResponse")
    public ChartResponse mass(ChartRequest request) {
        //方法用于群发测试
        System.out.println("name = " + request.getName());
        System.out.println("content = " + request.getContent());
        ChartResponse response = new ChartResponse();
        response.setName(request.getName());
        response.setContent(request.getContent());
        return response;
    }

    //单独聊天
    @MessageMapping("/aloneRequest")
    public ChartResponse alone(ChartRequest request) {
        //方法用于一对一测试
        System.out.println("userId = " + request.getUserId());
        System.out.println("name = " + request.getName());
        System.out.println("content = " + request.getContent());
        ChartResponse response = new ChartResponse();
        response.setName(request.getName());
        response.setContent(request.getContent());
        this.template.convertAndSendToUser(request.getUserId(), "/alone/getResponse", response);
        return response;
    }
}
